package servlet;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import dao.DaoFactory;
import dao.UserDao;
import entity.User;

public class UserServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String uri=request.getRequestURI();
		String action = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
		if("jsonarray".equals(action)){
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out = response.getWriter();
			UserDao dao= DaoFactory.getInstance(UserDao.class);
			try {
				List<User> list = dao.findAll();
				JSONArray json = JSONArray.fromObject(list);
				out.println(json.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.flush();
			out.close();
		}else if("/jsonobject".equals(action)){
			response.setContentType("text/plain;charset=utf-8");
			PrintWriter out = response.getWriter();
			UserDao dao= DaoFactory.getInstance(UserDao.class);
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				User u = dao.findById(id);
				JSONObject json = JSONObject.fromObject(u);
				out.println(json.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.flush();
			out.close();
		}else{
			response.setContentType("text/plain;charset=utf-8");
			PrintWriter out = response.getWriter();
			UserDao dao= DaoFactory.getInstance(UserDao.class);
			try {
				List<User> list = dao.findAll();
				JSONArray json = JSONArray.fromObject(list);
				out.println(json.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
			out.flush();
			out.close();
		}
		
	}
}
